import React, {useEffect, useRef, useState} from "react";
import * as monaco from 'monaco-editor';

export default function (props) {
    const editorRef = useRef();
    const {
        code,
        onChange,
    } = props;
    useEffect(() => {
        editorRef.current = monaco.editor.create(document.getElementById('editor'), {
            value: code,
            language: 'javascript',
        });
        const model = editorRef.current.getModel();
        // jsx支持
        monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
            jsx: monaco.languages.typescript.JsxEmit.React,
            jsxFactory: 'React.createElement',
            reactNamespace: 'React',
            allowNonTsExtensions: true,
            allowJs: true,
            target: monaco.languages.typescript.ScriptTarget.Latest,
        });
        // model set
        monaco.editor.setModelLanguage(model, 'javascript');
    }, []);
    // Update editor with new external value
    useEffect(() => {
        if (editorRef.current && code !== editorRef.current.getValue()) {
            editorRef.current.setValue(code);
        }
    }, [code]);
    useEffect(() => {
        if (!editorRef.current) {
            return;
        }
        editorRef.current.onDidChangeModelContent(() => {
            onChange(editorRef.current.getValue());
        });
    }, [onChange]);

    return (
        <div id="editor" style={{
            height: 500,
            border: '1px solid #ccc'
        }} />
    )
};